package com.medical_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.medical_backend.entity.Menu;
import com.medical_backend.entity.Result;
import com.medical_backend.entity.User;
import com.medical_backend.service.MenuService;
import com.medical_backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @GetMapping("/getall")
    public Result getAll(){
        return new Result("查询成功",menuService.list(),200);
    }

    @GetMapping("/usersWithRoles")
    public Result getUsersWithRoles(@RequestParam(required = false) String keyword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.like("userid", keyword);
        }

        List<User> allUsers = userService.list(queryWrapper);  // 按条件查询用户

        List<Menu> allMenus = menuService.list();  // 所有权限表

        // 将菜单按 userid 分组
        Map<String, List<String>> roleMap = allMenus.stream()
                .collect(Collectors.groupingBy(Menu::getUserid,
                        Collectors.mapping(Menu::getHref, Collectors.toList())));

        // 构造用户+权限结果
        List<Map<String, Object>> result = allUsers.stream().map(user -> {
            Map<String, Object> map = new HashMap<>();
            map.put("userid", user.getUserid());
            map.put("hrefs", roleMap.getOrDefault(user.getUserid(), new ArrayList<>()));
            return map;
        }).collect(Collectors.toList());

        return new Result("查询成功", result, 200);
    }

    @GetMapping("/getrole/{userid}")
    public Result getrole(@PathVariable("userid") String userid){
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<Menu>();
        queryWrapper.eq("userid",userid);
        return new Result("查询成功", menuService.list(queryWrapper),200);
    }

    @PostMapping("/update")
    public Result update(@RequestBody Menu menu){
        return new Result("修改成功",menuService.updateById(menu),200);
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Long id){
        return new Result("删除成功",menuService.removeById(id),200);
    }
    /*
     *根据传入的第一个菜单对象的用户ID，删除该用户相关的所有菜单
     * 遍历传入的菜单列表，逐个保存到数据库中
     */
    @PostMapping("/add")
    public Result add(@RequestBody List<Menu> menus){
        menuService.removeByUserid(menus.get(0).getUserid());
        for(Menu menu: menus){
            menuService.save(menu);
        }
        return new Result("添加成功",null,200);
    }
}
